const express = require('express')
//创建express服务器
const app = express()
//导入cors模块，处理跨域问题
const cors = require('cors')
app.use(cors())
//解析post数据请求
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
const joi = require('joi')
//在路由之前封装一个全局res
app.use((req, res, next) => {
    //封装一个全局res status默认为1
    res.cc = function (err, status = 1) {
        res.send({
            status,
            message: err instanceof Error?err.message:err
        })
    }
    next()
})
//导入config配置文件
const config = require('./config')
//解析token中间件 express-jwt
const expressJWT = require('express-jwt')
app.use(expressJWT({secret:config.jwtSecretKey}).unless({path:[/^\/api/]}))
app.use((err,req,res,next)=>{
    if(err.name == 'UnauthorizedError') return res.cc('身份认证失败！')
    res.cc(err)
})

//导入路由模块
const employeeRouter = require('./router/employee')
app.use('/api', employeeRouter)
const testTokenRouter = require('./router/testToken')
app.use('/my',testTokenRouter)
const deptRouter = require('./router/dept')
app.use('/my',deptRouter)
const empRouter = require('./router/emp')
app.use('/my',empRouter)
//解析验证规则错误中间件
app.use((err,req,res,next)=>{
    if (err instanceof joi.ValidationError) return res.cc(err)
    res.cc(err)
})


app.listen(5001, () => {
    console.log('api server running at http://127.0.0.1:5001');
})